package com.huanletao.quartz.config;

import com.huanletao.quartz.entity.JobDetails;
import com.huanletao.quartz.schedule.DefaultQuartzSchedule;
import com.huanletao.quartz.schedule.QuartzDataManager;
import com.huanletao.quartz.schedule.QuartzDataManagerImpl;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import javax.sql.DataSource;
import java.util.List;

/**
 * description: QuartzStarter <br>
 * date: 2022/7/5 16:11 <br>
 * author: 踏雪无痕 <br>
 * since: 1.0 <br>
 */
public class QuartzScheduleFactoryBean implements FactoryBean<DefaultQuartzSchedule>, InitializingBean {

    private QuartzDataManager quartzDataManager;
    private DefaultQuartzSchedule quartzSchedule;
    private DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public QuartzDataManager getQuartzDataManager() {
        return quartzDataManager;
    }

    @Override
    public DefaultQuartzSchedule getObject() throws Exception {
        if (quartzSchedule==null)
         buildQuartSchedule();
        return quartzSchedule;
    }

    private DefaultQuartzSchedule buildQuartSchedule() throws SchedulerException {
        quartzSchedule = new DefaultQuartzSchedule();
        System.out.println("quartzDataManager = " + quartzDataManager);
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        scheduler.start();
        quartzSchedule.setScheduler(scheduler);
        quartzDataManager = new QuartzDataManagerImpl(dataSource);
        List<JobDetails> jobDetails = quartzDataManager.selectRunJobs();
        for (JobDetails jobDetail : jobDetails) {
            //非分布式环境；
            quartzSchedule.addQuartzJob(jobDetail);
        }
        return quartzSchedule;
    }

    @Override
    public Class<DefaultQuartzSchedule> getObjectType() {
        return DefaultQuartzSchedule.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        buildQuartSchedule();
    }
}
